﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Reflection;
using System.Resources;
using System.ComponentModel;

namespace TorchLightSettings
{
    public class TLSettings : INotifyPropertyChanged
    {
        private TLKeyBindings _keyBindings;

        public event PropertyChangedEventHandler PropertyChanged;

        public TLKeyBindings KeyBindings
        {
            get { return _keyBindings; }
            set
            {
                _keyBindings = value;
                NotifyPropertyChanged("KeyBindings");
            }
        }

        public TLSettings()
        {
            KeyBindings = new TLKeyBindings();
        }

        public void Load(string path)
        {
            TextReader reader = new StreamReader(path);

            PropertyInfo propertyInfo = null;
            Type type = this.GetType();

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                int seperatorLoc = line.IndexOf(" :");
                string match = line.Substring(0, seperatorLoc);

                string settingName;
                if ((settingName = SettingsMappings.ResourceManager.GetString(match)) != null)
                {
                    string[] propertyMap = settingName.Split(new char[] { '.' });

                    Type propertyType = this.GetType();
                    for (int i = 0; i < propertyMap.Count(); i++)
                    {
                        propertyInfo = propertyType.GetProperty(propertyMap[i]);
                        propertyType = propertyInfo.PropertyType;

                        if (propertyInfo == null)
                            break;
                    }

                    if (propertyInfo != null)
                    {
                        Object typeInstance = null;

                        if (propertyInfo.DeclaringType == KeyBindings.GetType())
                            typeInstance = KeyBindings;
                        else if (propertyInfo.DeclaringType == this.GetType())
                            typeInstance = this;

                        propertyInfo.SetValue(typeInstance, Convert.ToInt32(line.Substring(seperatorLoc + 2)), null);

                    }
                }
            }
        }

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
